<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Services\LoginUser;
use App\Models\User;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        // 绑定LoginUser为一个单例
        // 返回包装了当前登录用户的一个对象
        $this->app->singleton(LoginUser::class, function ($app) {
            $session = app('session');
            if ($session->has('user')) {
                $id = $session->get('user');
                $user = User::where('id', $id)->first();
            } else {
                $user = null;
            }
            return new LoginUser($user);
        });
    }
}
